<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexDB 前端数据库</title>
</head>

<body>
    <script>
        // var a = 2;
        // const request = 1;
        // index 索引
        var db;
        var request = window.indexedDB.open('blogs', 2);
        // console.log(request);
        request.onerror = function(event) {
            console.log('数据库打开失败');
        }
        request.onsuccess = function(event) {
            db = request.result;
            create();
            console.log('数据库打开成功');
            // var objectStore = db.createObjectStore('person', {
            //     keyPath: 'id'
            // });
        };
        request.onupgradeneeded = function() {
            db = request.result;
            var objectStore;
            if (!db.objectStoreNames.contains('person')) {
                // 主键 索引就是为了查询更快 doc(id) 详情页 加一个索引
                // 列表 .get() 20 .skip() limit()
                // 详情页 /detail?id-121212
                objectStore = db.createObjectStore('person', {
                    keyPath: 'id'
                });
                // /search?name=%xiaolang%  name 字典部首一样做一个索引
                objectStore.createIndex('name', 'name', {
                    unique: false //这个索引不是唯一索引
                })
                objectStore.createIndex('email', 'email', {
                    unique: true //这个索引是唯一索引 
                })
            }
        }

        function create() {
            // 事务
            var request = db.transaction(['person'], 'readwrite')
                .objectStore('person')
                .add({
                    id: 1,
                    name: '熊汉挺',
                    age: '24',
                    email: 'xt@tmall.com'
                })
            request.onsuccess = function() {
                console.log('数据写入成功');
            }
            request.onerror = function() {
                console.log('数据系写入失败');
            }
        }
    </script>
</body>

</html>